package com.css.service;

import com.css.config.base.SpringContext;
import com.css.config.netty.IoSession;
import com.css.config.netty.enums.SessionCloseReason;
import com.css.config.netty.enums.SessionManager;
import com.css.dao.UserMapper;
import com.css.logic.user.message.res.ResUserInfo;
import com.css.util.commonutil.ConcurrentHashSet;
import com.css.util.model.LruHashMap;
import com.css.util.model.User;
import com.css.util.netty.ChannelUtils;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Set;

/**
 * @author zyj
 * @description
 * @date 2019/7/19 11:30
 **/
@Service
public class UserService {

    @Autowired
    private UserMapper userDao;

    /** 在线用户列表　*/
    private Set<Long> onlneUsers = new ConcurrentHashSet<>();

    /** lru缓存最近登录的所有用户 */
    private Map<Long, User> lruUsers = new LruHashMap<>(1000);

    /**
     * 根据用户id获取在线用户信息
     * @author zyj
     * @date 2019/7/25 16:44
     */
    public User getOnlineUser(long userId) {
        return this.lruUsers.get(userId);
    }

    public void addUser2Online(User user) {
        this.onlneUsers.add(user.getUserId());
        this.lruUsers.put(user.getUserId(), user);
    }

    public boolean isOnlineUser(long userId) {
        return this.onlneUsers.contains(userId);
    }

    public void userLogout(Channel channel, SessionCloseReason reason) {
        IoSession session = ChannelUtils.getSessionBy(channel);
        long userId = session.getUser().getUserId();
        SpringContext.getUserService().removeFromOnline(userId);
        SpringContext.getFriendService().onUserLogout(userId);

        SessionManager.INSTANCE.ungisterUserContext(channel, reason);
    }

    public void removeFromOnline(long userId) {
        this.onlneUsers.remove(userId);
    }

    public User queryUser(long userId, String password) {
        if (userId <= 0 || StringUtils.isEmpty(password)) {
            return null;
        }
        com.css.entity.User users = userDao.selectByPrimaryKey(userId);
        User user = new User(users);
        if (user != null &&
                user.getPassword().equals(password)) {
            return user;
        }

        return null;
    }


    public void refreshUserProfile(User user) {
        ResUserInfo response = new ResUserInfo();
        response.setSex(user.getSex());
        response.setUserId(user.getUserId());
        response.setUserName(user.getUserName());
        response.setSignature(user.getSignature());

        SessionManager.INSTANCE.sendPacketTo(user.getUserId(), response);
    }


}
